<template>
  <div id="main">
    <h2>员工考勤管理</h2>
    <div class="head">
      <!-- <el-button id="tianjia" type="primary" style="margin:20px;flex:right;" @click="handleOpen('添加考勤', 1)">添加考勤</el-button> -->
      <el-input v-model="searchTableInfo" placeholder="请输入搜索内容" style="width:240px;float: right;margin:30px;" />
    </div>
    <div id="search">
      <el-form ref="attendanceStaff" :model="attendanceStaff" label-position="top">
        <el-row type="flex" justify="">
          <el-col :span="4">
            <el-form-item
              prop="staffId"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="attendanceStaff.staffId"
                filterable
                placeholder="请选择要查看的教师"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in teacher"
                  :key="item.staffId"
                  :label="item.String"
                  :value="item.staffId"
                />
              </el-select>
            </el-form-item></el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              style="margin-left:10px"
              @click="handleSerch(attendanceStaff)"
            >查询</el-button></el-col>
          <!-- </el-row>

      <el-row type="flex" justify="">-->
          <el-col :span="5">
            <el-form-item
              prop="classId"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="attendanceStaff.classId"
                filterable
                placeholder="请选择班级"
                style="width: 90%;"
              >
                <el-option
                  v-for="item in clazz"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                />
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item
              prop="completionTimes"
              :label-width="formLabelWidth"
            >
              <el-input
                v-model="attendanceStaff.completionTimes"
                placeholder="请输入第几节课（1-17）"
                autocomplete="off"
                maxlength="20"
                show-word-limit
                style="width: 90%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              style="margin-top:0px"
              @click="handleClass(attendanceStaff)"
            >查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="staffName"
          label="员工姓名"
          width="120"
        />
        <el-table-column
          align="center"
          prop="className"
          label="班级"
          width="120"
        />
        <el-table-column
          align="center"
          prop="attStatus"
          label="出勤情况"
          width="120"
        />
        <el-table-column
          align="center"
          prop="completionTimes"
          label="上课次数"
          width="100"
        />
        <el-table-column
          align="center"
          prop="reasonAbsence"
          label="缺勤原因"
        />
        <el-table-column
          align="center"
          prop="postTime"
          label="打卡时间"
          width="160"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改考勤', 2, Scope.row.attTeaId)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.attTeaId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="attendanceStaff" :model="attendanceStaff" label-position="top" :rules="rules">
        <el-form-item prop="classId" label="班级名称" :label-width="formLabelWidth">
          <el-select v-if="editType == 2" v-model="attendanceStaff.classId" filterable placeholder="请选择" style="width: 40%;" @change="getstudents2">
            <el-option
              v-for="item in clazz"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
          <el-select v-if="editType == 1" v-model="attendanceStaff.classId" filterable placeholder="请选择" style="width: 40%;" @change="getstudents">
            <el-option
              v-for="item in clazz"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="teacherId" label="教师姓名" :label-width="formLabelWidth">
          <el-select v-model="attendanceStaff.teacherId" filterable placeholder="请选择" style="width: 40%;">
            <el-option
              v-for="item in teacher"
              :key="item.staffId"
              :label="item.String"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="completionTimes" label="上课次数" :label-width="formLabelWidth">
          <el-input v-model="attendanceStaff.completionTimes" autocomplete="off" maxlength="30" show-word-limit />
        </el-form-item>

        <el-form-item prop="attendance" label="出勤情况" :label-width="formLabelWidth">
          <el-select v-model="attendanceStaff.attendance" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="attendanceStaff.attendance == 0" prop="reasonAbsence" label="缺勤原因" :label-width="formLabelWidth">
          <el-input v-model="attendanceStaff.reasonAbsence" autocomplete="off" maxlength="30" show-word-limit />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="editType == 2" type="primary" @click="handleUpdate('attendanceStaff')">修 改</el-button>
        <el-button v-if="editType == 1" type="primary" @click="handleAddUser('attendanceStaff')">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  deleteAtt,
  getAllAtt,
  addAttTea,
  getAttbyId,
  getStudentString,
  getTeacherString,
  getClassString,
  getSearchAttAll,
  getSearchAttAllBycalssId,
  updateAttById
} from '@/api/attendanceTea'
import { getInfo } from '@/api/user'
import { getAllClass } from '@/api/class'
export default {
  data() {
    return {
      options: [
        {
          value: 1,
          label: '出勤'
        },
        {
          value: 0,
          label: '缺勤'
        }
      ],
      newAtt: {
        attTeaId: '',
        studentName: '',
        className: '',
        attStatus: '',
        staffName: '',
        completionTimes: '',
        reasonAbsence: '',
        postTime: ''
      },
      value: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      // list: [],
      tableList: [],
      searchTableInfo: '',
      attendanceStaff: [],
      attendanceTea: [],
      listLoading: false,
      dialogFormVisible: false,
      editType: 1, // 1 添加 2 修改
      child: {},
      staffId: {},
      // staff{},
      teacher: {},
      clazz: {},
      search: '',
      formLabelWidth: '200px',
      rules: {
        attendance: [
          { required: true, message: '出勤情况不能为空', trigger: 'blur' }
        ],
        classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],

        studentId: [
          { required: true, message: '学生姓名不能为空', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '教师姓名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.fetchData()
    this.getAllTeacher()
    this.getAllClass()
    // getInfo()
  },
  methods: {
    // getInfo: function(){
    //   getAllClass().then((resp) => {
    //     this.clazz = resp.obj
    //     console.log(this.clazz)
    //   })
    // },
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    getAllChild(id) {
      getStudentString(id).then(res => {
        this.child = res.obj
      })
    },
    getAllTeacher() {
      getTeacherString().then(res => {
        this.teacher = res.obj
      })
    },
    getAllClass() {
      getClassString().then(res => {
        this.clazz = res.obj
      })
    },
    handleClick(row) {
      console.log(row)
    },

    handleSerch(attendanceStaff) {
      console.log('查询按钮发送的信息', attendanceStaff)
      this.tableList = []
      console.log('CNMDshabi', this.tableList)
      this.listLoading = true

      getSearchAttAllBycalssId(attendanceStaff).then(data => {
        console.log('发送的数据', attendanceStaff)
        console.log('只查老师得到的data', data)
        this.newAtt

        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attTeaId = data.obj[i].attTeaId
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },

    handleClass(attendanceStaff) {
      console.log('确定按钮发送的信息XXXXXX', attendanceStaff)

      this.tableList = []

      console.log(this.tableList, '哈哈哈')
      this.listLoading = true
      getSearchAttAll(attendanceStaff).then(data => {
        console.log('查班级+上课次数得到的data', data)
        this.newAtt

        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attTeaId = data.obj[i].attTeaId
          // this.newAtt.studentName = data.obj[i].studentName
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }
        console.log(this.tableList)
        this.listLoading = false
      })
    },
    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllAtt().then(data => {
        console.log('页面开始刷新时得到的信息', data)
        this.newAtt
        for (var i = 0; i < data.obj.length; i++) {
          this.newAtt.attTeaId = data.obj[i].attTeaId
          this.newAtt.className = data.obj[i].clazz.className
          this.newAtt.staffName = data.obj[i].staff.staffName
          this.newAtt.completionTimes = data.obj[i].completionTimes
          this.newAtt.reasonAbsence = data.obj[i].reasonAbsence
          if (data.obj[i].reasonAbsence === null) {
            this.newAtt.reasonAbsence = '已出勤'
          }
          this.newAtt.postTime = data.obj[i].postTime
          if (data.obj[i].attendance === 0) {
            this.newAtt.attStatus = '未出勤'
          }
          if (data.obj[i].attendance === 1) {
            this.newAtt.attStatus = '已出勤'
          }
          this.tableList.push(this.newAtt)
          this.newAtt = {}
        }

        console.log(this.tableList)
        this.listLoading = false
      })
    },

    handleDelete(id, username) {
      this.$confirm('确认删除条考勤？').then(() =>
        deleteAtt(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },

    handleAddUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addAttTea(this.attendanceStaff).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.attendanceStaff = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.attendanceStaff = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getAttbyId(id).then(resp => {
          console.log('id为：', id)
          console.log(resp)
          this.attendanceStaff = resp.obj[0]

          // console.log('this.attendancestaff：', this.attendanceStaff)
          this.attendanceStaff.attTeaId = String(this.attendanceStaff.attTeaId)
          console.log(this.attendanceStaff)
        })
      }
    },

    // handleOpen(title, type, id) {
    //   this.attendanceStaff = {}
    //   this.dialogFormVisible = true
    //   this.title = title
    //   this.editType = type
    //   if (type === 2) {
    //     getAttbyId(id).then(resp => {
    //       console.log('resp的信息', resp)
    //       for (var i = 0; i < resp.obj.length; i++) {
    //         this.attendanceStaff.attTeaId = resp.obj[i].attTeaId
    //         this.attendanceStaff.classId = resp.obj[i].classId
    //         this.attendanceStaff.teacherId = resp.obj[i].teacherId
    //         this.attendanceStaff.className = resp.obj[i].clazz.className
    //         this.attendanceStaff.staffName = resp.obj[i].staff.staffName
    //         this.attendanceStaff.completionTimes = resp.obj[i].completionTimes
    //         this.attendanceStaff.reasonAbsence = resp.obj[i].reasonAbsence
    //         if (resp.obj[i].reasonAbsence === null) {
    //           this.attendanceStaff.reasonAbsence = '已出勤'
    //         }
    //         this.attendanceStaff.postTime = resp.obj[i].postTime
    //         if (resp.obj[i].attendance === 0) {
    //           this.attendanceStaff.attStatus = '未出勤'
    //         }
    //         if (resp.obj[i].attendance === 1) {
    //           this.attendanceStaff.attStatus = '已出勤'
    //         }
    //         console.log(this.attendanceStaff)
    //       }

    //       // console.log(resp)
    //       // this.attendanceStaff = resp.obj
    //       // this.attendanceStaff.teacherId = String(this.attendanceStaff.teacherId)
    //       // console.log(this.attendanceStaff)

    //       // getStudentString(this.attendanceStu.classId).then(resp => {
    //       //   this.child = resp.obj
    //       // })
    //     })
    //   }
    // },

    getstudents() {
      getStudentString(this.attendanceStaff.classId).then(resp => {
        this.child = resp.obj
      })
    },
    getstudents2(value) {
      getStudentString(this.attendanceStaff.classId).then(resp => {
        this.child = resp.obj
      })
      this.attendanceStaff.studentId = ''
    },
    handleClose() {
      this.dialogFormVisible = false
      this.attendanceStaff = {}
    },
    attendance(row, column) {
      if (row.attendance === 0) {
        return '缺勤'
      }
      if (row.attendance === 1) {
        return '出勤'
      }
    },

    handleUpdate(formName) {
      console.log('this.attendanceStaff', this.attendanceStaff)
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.attendanceStaff)
          updateAttById(this.attendanceStaff).then(resp => {
            console.log('this.attendanceStaff', this.attendanceStaff)
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.attendanceTea()
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    }

  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
#search{
  width: 1500px;
  margin-left: 20px;
}
/* #tianjia{
  border: 1px solid black;
  float: right;
  margin-top: -10px;
} */
</style>
